<template>
  <div class="app-container">
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          @click="handleAdd"
        >
          <el-icon><Plus /></el-icon>
          新增
        </el-button>
      </el-col>
      <el-col :span="6">
        <el-input
          v-model="searchAreaName"
          placeholder="请输入区域名称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-col>
      <el-col :span="1.5">
        <el-button type="primary" @click="handleQuery">
          <el-icon><Search /></el-icon>
          搜索
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button @click="resetQuery">
          <el-icon><Refresh /></el-icon>
          重置
        </el-button>
      </el-col>
    </el-row>

    <el-table v-loading="loading" :data="areaList">
      <el-table-column label="区域名称" align="center" prop="areaName" />
      <el-table-column label="地区" align="center">
        <template #default="scope">
          {{ scope.row.province }}-{{ scope.row.city }}-{{ scope.row.district }}
        </template>
      </el-table-column>
      <el-table-column label="详细地址" align="center" prop="address" />
      <el-table-column label="经度" align="center" prop="longitude" />
      <el-table-column label="纬度" align="center" prop="latitude" />
      <el-table-column label="区域面积" align="center" prop="areaSize" />
      <el-table-column label="风力等级" align="center" prop="windLevel" />
      <el-table-column label="状态" align="center" prop="status">
        <template #default="scope">
          <el-tag :type="scope.row.status === 1 ? 'success' : 'info'">{{ scope.row.status === 1 ? '启用' : '禁用' }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="关联设备数" align="center" prop="deviceRelationCount" />
      <el-table-column label="操作" align="center" class="link-type" width="150">
        <template #default="scope">
          <el-button type="text" @click="handleUpdate(scope.row)">
            <el-icon><Edit /></el-icon>
            修改
          </el-button>
          <el-button type="text" @click="handleDelete(scope.row)">
            <el-icon><Delete /></el-icon>
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- Add/Edit dialog -->
    <el-dialog :title="dialogTitle" v-model="dialogVisible" width="500px" append-to-body>
      <el-form ref="areaFormRef" :model="areaForm" :rules="rules" label-width="100px">
        <el-form-item label="区域名称" prop="areaName">
          <el-input v-model="areaForm.areaName" placeholder="请输入区域名称" />
        </el-form-item>
        <el-form-item label="省份" prop="province">
          <el-select v-model="areaForm.province" placeholder="请选择省份" @change="fetchCities">
            <el-option v-for="item in provinceList" :key="item.id" :label="item.name" :value="item.name" />
          </el-select>
        </el-form-item>
        <el-form-item label="城市" prop="city">
          <el-select v-model="areaForm.city" placeholder="请选择城市" @change="fetchAreas">
            <el-option v-for="item in cityList" :key="item.id" :label="item.name" :value="item.name" />
          </el-select>
        </el-form-item>
        <el-form-item label="区县" prop="district">
          <el-select v-model="areaForm.district" placeholder="请选择区县">
            <el-option v-for="item in areaListForDropdown" :key="item.id" :label="item.name" :value="item.name" />
          </el-select>
        </el-form-item>
        <el-form-item label="详细地址" prop="address">
          <el-input v-model="areaForm.address" placeholder="请输入详细地址" />
        </el-form-item>
        <el-form-item label="经度" prop="longitude">
          <el-input v-model="areaForm.longitude" placeholder="请输入经度" type="number" />
        </el-form-item>
        <el-form-item label="纬度" prop="latitude">
          <el-input v-model="areaForm.latitude" placeholder="请输入纬度" type="number" />
        </el-form-item>
        <el-form-item label="区域面积" prop="areaSize">
          <el-input v-model="areaForm.areaSize" placeholder="请输入区域面积" type="number" />
        </el-form-item>
        <el-form-item label="风力等级" prop="windLevel">
          <el-input v-model="areaForm.windLevel" placeholder="请输入风力等级" type="number" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="areaForm.status" placeholder="请选择状态">
            <el-option label="启用" :value="1"></el-option>
            <el-option label="禁用" :value="0"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import { getAreaInfoList, addAreaInfo, updateAreaInfo, deleteAreaInfo } from '@/api/device/region';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Plus, Search, Refresh, Edit, Delete } from '@element-plus/icons-vue'; // Import icons
import { getProvince, getCity, getArea } from '@/api/index'; // Import location APIs

const areaList = ref([]);
const loading = ref(true);
const dialogVisible = ref(false);
const dialogTitle = ref('');
const areaFormRef = ref(null);

// Location dropdown data
const provinceList = ref([]);
const cityList = ref([]);
const areaListForDropdown = ref([]);

const searchAreaName = ref('');

const areaForm = reactive({
  areaId: null,
  areaName: '',
  province: '',
  city: '',
  district: '',
  address: '',
  longitude: null,
  latitude: null,
  areaSize: null,
  windLevel: null,
  status: 1,
});

const rules = {
  areaName: [{ required: true, message: "区域名称不能为空", trigger: "blur" }],
  // Removed validation for province, city, district as select handles required
  address: [{ required: true, message: "详细地址不能为空", trigger: "blur" }],
  longitude: [{ required: true, message: "经度不能为空", trigger: "blur" }],
  latitude: [{ required: true, message: "纬度不能为空", trigger: "blur" }],
  areaSize: [{ required: true, message: "区域面积不能为空", trigger: "blur" }],
  windLevel: [{ required: true, message: "风力等级不能为空", trigger: "blur" }],
  status: [{ required: true, message: "状态不能为空", trigger: "change" }],
};

/** 查询设备投放区域列表 */
function getList(params) {
  loading.value = true;
  getAreaInfoList(params).then(response => {
    if (response.code === 200) {
      areaList.value = response.data;
    } else {
      ElMessage.error(response.msg || '获取区域列表失败');
      areaList.value = [];
    }
    loading.value = false;
  }).catch(() => {
    loading.value = false;
  });
}

/** 搜索按钮操作 */
function handleQuery() {
  getList({ areaName: searchAreaName.value });
}

/** 重置查询 */
function resetQuery() {
  searchAreaName.value = ''; // Clear the search input
  getList(); // Fetch the full list
}

/** 获取省份列表 */
function fetchProvinces() {
  getProvince().then(response => {
    // Assuming response is an array of objects with id and name properties
    provinceList.value = response;
  });
}

/** 根据省份ID获取城市列表 */
function fetchCities(provinceName) {
  cityList.value = [];
  areaListForDropdown.value = [];
  areaForm.city = '';
  areaForm.district = '';
  if (provinceName) {
    const selectedProvince = provinceList.value.find(p => p.name === provinceName);
    if (selectedProvince) {
      getCity(selectedProvince.id).then(response => {
        // Assuming response is an array of objects with id and name properties
        cityList.value = response;
      });
    }
  }
}

/** 根据城市ID获取区县列表 */
function fetchAreas(cityName) {
  areaListForDropdown.value = [];
  areaForm.district = '';
  if (cityName) {
    const selectedCity = cityList.value.find(c => c.name === cityName);
    if (selectedCity) {
      getArea(selectedCity.id).then(response => {
        // Assuming response is an array of objects with id and name properties
        areaListForDropdown.value = response;
      });
    }
  }
}

/** 处理新增按钮 */
function handleAdd() {
  resetForm();
  fetchProvinces(); // Fetch provinces when adding
  dialogVisible.value = true;
  dialogTitle.value = '添加设备投放区域';
}

/** 处理修改按钮 */
async function handleUpdate(row) {
  resetForm();
  Object.assign(areaForm, row);
  dialogTitle.value = '修改设备投放区域';
  dialogVisible.value = true;

  // Fetch location data for editing
  await fetchProvinces();
  // Need to find the provinceId, cityId, districtId based on the names in the row
  // This requires mapping names to IDs, which is not directly available in the provided APIs.
  // For now, I'll just fetch cities and areas assuming the names can be used to find IDs,
  // but a more robust solution would involve a backend endpoint to get location IDs by name.

  // This part is a placeholder and needs actual logic to find IDs by name
  const selectedProvince = provinceList.value.find(p => p.name === row.province);
  if (selectedProvince) {
    await fetchCities(selectedProvince.name);
    const selectedCity = cityList.value.find(c => c.name === row.city);
    if (selectedCity) {
      await fetchAreas(selectedCity.name);
    }
  }
}

/** 处理删除按钮 */
function handleDelete(row) {
  ElMessageBox.confirm(`是否确认删除区域名称为"${row.areaName}"的数据项？`,
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(() => {
      deleteAreaInfo(row.areaId).then(() => {
        ElMessage.success('删除成功');
        getList();
      }).catch(error => {
        ElMessage.error('删除失败: ' + (error.msg || error.message || '未知错误'));
      });
    })
    .catch(() => {});
}

/** 提交表单 */
function submitForm() {
  areaFormRef.value.validate(valid => {
    if (valid) {
      // Need to convert selected location names back to IDs if backend expects IDs for add/update
      // This is not explicitly clear from the provided backend code.
      // Assuming for now that the backend can handle names or the form object already has IDs if available.

      if (areaForm.areaId != null) {
        updateAreaInfo(areaForm).then(response => {
          ElMessage.success('修改成功');
          dialogVisible.value = false;
          getList();
        }).catch(error => {
          ElMessage.error('修改失败: ' + (error.msg || error.message || '未知错误'));
        });
      } else {
        addAreaInfo(areaForm).then(response => {
          ElMessage.success('新增成功');
          dialogVisible.value = false;
          getList();
        }).catch(error => {
          ElMessage.error('新增失败: ' + (error.msg || error.message || '未知错误'));
        });
      }
    }
  });
}

/** 取消按钮 */
function cancel() {
  dialogVisible.value = false;
  resetForm();
}

/** 表单重置 */
function resetForm() {
  areaForm.areaId = null;
  areaForm.areaName = '';
  areaForm.province = '';
  areaForm.city = '';
  areaForm.district = '';
  areaForm.address = '';
  areaForm.longitude = null;
  areaForm.latitude = null;
  areaForm.areaSize = null;
  areaForm.windLevel = null;
  areaForm.status = 1;
  // Clear dropdown data on reset
  provinceList.value = [];
  cityList.value = [];
  areaListForDropdown.value = [];
  if (areaFormRef.value) {
    areaFormRef.value.resetFields();
  }
}

onMounted(() => {
  getList();
});
</script>

<style scoped>
/* Add your styles here */
.app-container {
  padding: 20px;
}
.mb8 {
  margin-bottom: 8px;
}
</style>
